package com.example.program.InterCeptor;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.example.program.pojo.Result;

import com.example.program.utils.JWT;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//拦截器 过滤器
@Component
public class interceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url=request.getRequestURI();
///2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if(url.contains("/login"))
        {
            //放行

            return true;
        }
//3.获取令牌
        String token=request.getHeader("token");
//4.判断令牌是否存在
        if(StringUtils.isEmpty(token))
        {
            Result error=Result.error("NOT_LOGIN");
            String not= JSONObject.toJSONString(error);
            response.getWriter().write(not);
            return false;
        }
//解析TOKEN
        try{
            JWT.parseJWT(token);
        }catch (Exception e)
        {
            Result error=Result.error("NOT_LOGIN");
            String not= JSONObject.toJSONString(error);
            response.getWriter().write(not);
            return false;
        }



        return true;
    }
}
